package com.sky.controller.user;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import com.sky.service.OrderDetailService;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController("UserOrderController")
@RequestMapping("/user/order")
@Slf4j
@Api("订单相关接口")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 提交订单
     */
    @ApiOperation("提交订单")
    @PostMapping("/submit")
    @Transactional
    public Result<OrderSubmitVO> submit(@RequestBody OrdersSubmitDTO ordersSubmitDTO) {
        Orders  order =new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        //处理各种业务异常（地址为空、购物车数据为空）
        AddressBook addressBook = addressBookService.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(lambdaQueryWrapper);
        if (list==null|| list.isEmpty()){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向Order表中插入一条数据
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Orders.UN_PAID);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setPhone(addressBook.getPhone());
        order.setConsignee(addressBook.getConsignee());
        order.setUserId(userId);
//        order.setAddress(addressBook.getDetail());
        orderService.save(order);
        //向Order_Detail 表中插入n条数据
        Long orderId = order.getId();
        List<OrderDetail> orderDetails=new ArrayList<>();
        list.stream().map((item)->{
            OrderDetail orderDetail=new OrderDetail();
            orderDetail.setName(item.getName());
            orderDetail.setOrderId(orderId);
            //判断是菜品还是套餐
            Long dishId = item.getDishId();
            if(dishId!=null){
                orderDetail.setDishId(dishId);
                String dishFlavor = item.getDishFlavor();
                if(dishFlavor!=null){
                    orderDetail.setDishFlavor(item.getDishFlavor());
                }
            }else{
                orderDetail.setSetmealId(item.getSetmealId());
            }
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            orderDetail.setImage(item.getImage());
            orderDetails.add(orderDetail);
//            orderDetailService.save(orderDetail);
            return item;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(orderDetails);
        //清空当前用户的购物车
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper=new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
        //封装VO返回结果
        OrderSubmitVO orderSubmitVO=new OrderSubmitVO();
        orderSubmitVO.setId(orderId);
        orderSubmitVO.setOrderNumber(order.getNumber());
        orderSubmitVO.setOrderAmount(order.getAmount());
        orderSubmitVO.setOrderTime(order.getOrderTime());
        return Result.success(orderSubmitVO);
    }

    /**
     * 支付
     */
    //TODO 点击即可支付，没有请求微信官方无法完成支付
    @ApiOperation("支付")
    @PutMapping("/payment")
    public Result payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO){
        String orderNumber = ordersPaymentDTO.getOrderNumber();
        LambdaQueryWrapper<Orders> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Orders::getNumber,orderNumber);
        Orders order = orderService.getOne(lambdaQueryWrapper);
        order.setStatus(2);
        order.setCheckoutTime(LocalDateTime.now());
        order.setPayStatus(1);
        orderService.updateById(order);
        OrderPaymentVO orderPaymentVO=new OrderPaymentVO();
        orderPaymentVO.setNonceStr("123456");
        orderPaymentVO.setPaySign("123456");
        orderPaymentVO.setTimeStamp("123456");
        orderPaymentVO.setSignType("123456");
        orderPaymentVO.setPackageStr("123456");
        //订单提醒,通过WebSocket 向浏览器发送消息
        Map map =new HashMap();
        map.put("type",1);//1表示来单提醒
        map.put("orderId",order.getId());//订单ID
        map.put("content","订单号："+orderNumber);//订单号
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        return Result.success(orderPaymentVO);
    }


}
